<template>
  <div class="custom-pool" v-loading="loading" element-loading-text="加载中...">
    <div class="custom-pool-head">
      <el-form inline :model="searchForm" class="demo-searchForm">
        <el-form-item>
          <el-select v-model="searchForm.srch_type" placeholder="请选择">
            <el-option label="客户名称" value="客户名称" />
            <el-option label="电话号码" value="电话号码" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="请输入查询内容" />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFun">查询</el-button>
          <el-button @click="resetFun">重置</el-button>
          <!-- <el-button type="primary">导出</el-button> -->
          <el-button type="success" @click="downloadFun">
            <template #icon>
              <el-icon>
                <IEpDownload />
              </el-icon>
            </template>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-form inline>
        <el-form-item>
          <el-button type="primary" @click="addPool" v-if="permissions">
            <template #icon>
              <el-icon>
                <IEpPlus />
              </el-icon>
            </template>
            增加
          </el-button>
          <!-- <el-button @click="uploadFun">
            <template #icon>
              <el-icon>
                <IEpUpload />
              </el-icon> </template
            >导入</el-button
          > -->
        </el-form-item>
      </el-form>
    </div>
    <div class="custom-pool-content">
      <el-table
        :data="tableData"
        border
        :height="store.tableHeight - 90"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column v-for="item in tableHead" :label="item.name">
          <template #default="{ row }">
            <el-button
              @click="customDetailFun(row)"
              v-if="item.field == 'name'"
              type="primary"
              link
            >
              {{ row[item.field] }}
            </el-button>
            <span v-else>
              {{ row[item.field] }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="created_at" width="170" />
        <el-table-column label="创建人姓名" prop="created_user" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button
              type="warning"
              v-if="lingqu_permissions"
              link
              @click="obtainFun(row)"
            >
              领取
            </el-button>
            <el-button
              v-if="permissions"
              type="success"
              link
              @click="shareFun(row)"
            >
              分配
            </el-button>
            <el-button
              v-if="permissions"
              type="primary"
              link
              @click="updateOpen(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="permissions"
              type="danger"
              link
              @click="delFun(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="custom-pool-content-pagination">
        <div>
          <el-button
            type="success"
            :disabled="selectData.length == 0"
            v-if="permissions"
            @click="allShareFun"
          >
            批量分配
          </el-button>
          <el-button
            type="primary"
            :disabled="selectData.length == 0"
            @click="allObtainFun"
            v-if="lingqu_permissions"
          >
            批量领取
          </el-button>
          <el-button
            v-if="permissions"
            type="danger"
            :disabled="selectData.length == 0"
            @click="allDelFun"
            >批量删除</el-button
          >
        </div>
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <!-- 新增 -->
  <addDialog ref="addDialogRef" @refreshTable="refreshTable" />
  <!-- 分配、领取 -->
  <shareDialog ref="shareDialogRef" @refreshList="refreshTable" />
  <!-- 详情 -->
  <drawerPage ref="drawerPageRef" />
  <!-- 上传
  <uploadPage ref="uploadPageRef" @updateList="updateList" /> -->
</template>
<script setup>
import { useCounterStore } from "@/stores/counter.js";
import {
  listApi,
  detailApi,
  deleteApi,
  exportApi,
} from "@/plugins/api/customer/manage/pool";
import addDialog from "./components/DialogPool.vue";
import shareDialog from "./components/DialogShare.vue";
import drawerPage from "./components/DrawerCustom.vue";
// import uploadPage from "./components/Pool-UploadFile.vue";
const store = useCounterStore();
let loading = ref(false);
let searchForm = ref({});
let tableHead = ref([]);
let tableData = ref([]);
let selectData = ref([]);
function handleSelectionChange(val) {
  selectData.value = val.map((item) => {
    return item.id;
  });
}
let permissions = computed(() => {
  let arr = store.userInfo.auth || [];
  if (arr.indexOf("manager") > -1 || arr.indexOf("boss") > -1) {
    return true;
  } else {
    return false;
  }
});
let lingqu_permissions = computed(() => {
  let arr = store.userInfo.auth || [];
  if (arr.indexOf("saler") > -1) {
    return true;
  } else {
    return false;
  }
});
// 分页
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val) => {
  pageSize.value = val;
  selectData.value = [];
  getData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  selectData.value = [];
  getData();
};
let searchData = ref({});
function searchFun() {
  let obj = { ...searchForm.value };
  if (searchForm.value.time) {
    obj.start_time = searchForm.value.time[0];
    obj.end_time = searchForm.value.time[1];
  }
  searchData.value = { ...obj };
  tableData.value = [];
  currentPage.value = 1;
  getData();
}
// 重置
function resetFun() {
  searchForm.value = {};
  searchData.value = {};
  tableData.value = [];
  currentPage.value = 1;

  getData();
}
function getData() {
  let obj = {
    page: currentPage.value,
    pageSize: pageSize.value,
    srch_type: searchForm.value.srch_type,
    keyword: searchForm.value.keyword,
    start_time: searchForm.value.time ? searchForm.value.time[0] : "",
    end_time: searchForm.value.time ? searchForm.value.time[1] : "",
  };
  loading.value = true;
  listApi(obj)
    .then((res) => {
      tableHead.value = res.fields.filter((item) => {
        return item.in_list == 1;
      });
      tableData.value = res.list;
      total.value = res.page.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
function refreshTable() {
  selectData.value = [];
  getData();
}
// 增加
let addDialogRef = ref(null);
function addPool() {
  addDialogRef.value.initFun("add");
}
// 编辑
function updateOpen(row) {
  detailApi({
    id: row.id,
  }).then((res) => {
    addDialogRef.value.initFun("update", res.customer || {});
  });
}
let shareDialogRef = ref(null);
// 领取
function obtainFun(row) {
  shareDialogRef.value.initFun("obtain", row);
}
// 批量领取
function allObtainFun(row) {
  let str = selectData.value.join(",");
  shareDialogRef.value.initFun("obtain", { id: str });
}
// 分配
function shareFun(row) {
  shareDialogRef.value.initFun("share", row);
}
// 批量分配
function allShareFun(row) {
  let str = selectData.value.join(",");
  shareDialogRef.value.initFun("share", { id: str });
}
// 删除
function delFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
// 批量删除
function allDelFun() {
  ElMessageBox.confirm("确认删除选中的数据，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let str = selectData.value.join(",");
      deleteApi({
        id: str,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        selectData.value = [];
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
// 详情
let drawerPageRef = ref(null);
function customDetailFun(row) {
  drawerPageRef.value.initFun(row, false, "pool");
}
// 导入
let uploadPageRef = ref(null);
function uploadFun() {
  uploadPageRef.value.initFun();
}
// 导出
function downloadFun() {
  let obj = { ...searchForm.value };
  if (searchForm.value.time) {
    obj.start_time = searchForm.value.time[0];
    obj.end_time = searchForm.value.time[1];
  }
  searchData.value = { ...obj };
  exportApi(obj).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "公海客户.xlsx");
    document.body.appendChild(link);
    link.click();
  });
}
function updateList() {
  getData();
}

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
.custom-pool {
  width: 100%;
  height: 100%;

  .custom-pool-head {
    white-space: nowrap;
  }

  .custom-pool-content-pagination {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
  }
}
</style>
